/**
 * menkor.com Inc.
 * Copyright (c) 2012-2019 All Rights Reserved.
 */
package com.blueskykong.concurrency.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author keets
 * @date 2019-10-10.
 */
public class SingleExecutorTest {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService es = Executors.newSingleThreadExecutor(new ThreadFactory() {
            final AtomicInteger threadNumber = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(null, r, "pool-spark" + threadNumber.getAndIncrement(), 0);
                t.setDaemon(true);
                System.out.println("Thread: " + Thread.currentThread().getName());
//                t.run();
                return t;
            }
        });
        es.submit(() -> {

            System.out.println("es: " + Thread.currentThread().getName());
        });
        List<Callable<String>> cs = new ArrayList<>();
        cs.add(() -> {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName());
            return "first";
        });
        cs.add(() -> {
            System.out.println(Thread.currentThread().getName());
            return "second";
        });

        Future<Object> f = es.submit((Callable) () -> {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName());
            return "zero";
        });
        List<Future<String>> fs = es.invokeAll(cs, 2000, TimeUnit.MILLISECONDS);
        for (Future<String> tmp : fs) {
            System.out.println(tmp.get());
        }
        es.shutdown();
        System.out.println("get rs: " + f.get());
    }
}
